import axios from 'axios';
import { API_BASE_URL, getAuthHeaders } from '../../../config/apiConfig';

// 私信消息接口
export interface PrivateMessage {
  id: number;
  messageId?: number; // 兼容API返回的messageId字段
  senderId: string;
  receiverId: string;
  senderName?: string;
  receiverName?: string;
  content: string;
  messageContent?: string; // 兼容API返回的messageContent字段
  timestamp?: string; // 兼容前端使用的timestamp字段
  sendTime?: string; // 兼容API返回的sendTime字段
  isRead: boolean;
}

// 用于防止重复请求的映射
const pendingRequests: Record<string, boolean> = {};

// 检查用户是否已登录
const checkUserLoggedIn = (): string => {
  const token = localStorage.getItem('token');
  if (!token) {
    throw new Error('用户未登录');
  }
  return token;
};

// 获取当前用户ID
const getCurrentUserId = (): string => {
  const userJson = localStorage.getItem('user');
  if (!userJson) {
    console.warn('用户信息不存在，可能未登录');
    return '';
  }
  
  try {
    const user = JSON.parse(userJson);
    if (!user || !user.id) {
      console.warn('用户ID不存在');
      return '';
    }
    return user.id.toString();
  } catch (error) {
    console.error('用户信息解析失败', error);
    return '';
  }
};

// 通过token获取用户信息
const getUserProfileByToken = async (): Promise<any> => {
  const token = localStorage.getItem('token');
  if (!token) {
    console.warn('Token不存在，用户可能未登录');
    return null;
  }
  
  try {
    const response = await fetch('/api/auth/profile', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (!response.ok) {
      throw new Error('获取用户信息失败');
    }
    
    const userData = await response.json();
    // 更新本地存储的用户信息
    localStorage.setItem('user', JSON.stringify(userData));
    return userData;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

export class MessageService {
  // 发送私信
  static async sendMessage(message: { receiverId: string; content: string }): Promise<PrivateMessage> {
    try {
      checkUserLoggedIn();
      
      // 构造符合API要求的请求体
      const requestBody = {
        receiverId: message.receiverId,
        messageContent: message.content // 使用messageContent而不是content
      };
      
      const response = await axios.post<any>(
        `${API_BASE_URL}/api/messages`,
        requestBody,
        { headers: getAuthHeaders() }
      );
      
      // 映射API返回的字段到前端使用的字段
      const mappedData = {
        id: response.data.messageId || response.data.id,
        senderId: response.data.senderId,
        receiverId: response.data.receiverId,
        senderName: response.data.senderName,
        receiverName: response.data.receiverName,
        content: response.data.messageContent || response.data.content,
        timestamp: response.data.sendTime || response.data.timestamp, // 优先使用sendTime
        isRead: response.data.isRead
      };
      
      return mappedData;
    } catch (error) {
      console.error('发送私信失败:', error);
      throw error;
    }
  }

  // 获取与特定用户的对话
  static async getConversation(userId: number): Promise<PrivateMessage[]> {
    try {
      checkUserLoggedIn();
      const response = await axios.get<any[]>(
        `${API_BASE_URL}/api/messages/conversation/${userId}`,
        { headers: getAuthHeaders() }
      );
      
      // 映射API返回的字段到前端使用的字段
      const mappedData = response.data.map(msg => ({
        id: msg.messageId || msg.id,
        senderId: msg.senderId,
        receiverId: msg.receiverId,
        senderName: msg.senderName,
        receiverName: msg.receiverName,
        content: msg.messageContent || msg.content,
        timestamp: msg.sendTime || msg.timestamp, // 优先使用sendTime
        isRead: msg.isRead
      }));
      
      return mappedData;
    } catch (error) {
      console.error('获取对话失败:', error);
      throw error;
    }
  }

  // 获取所有对话列表
  static async getConversations(): Promise<Conversation[]> {
    try {
      const currentUserId = getCurrentUserId();
      if (!currentUserId) {
        console.warn('获取用户ID失败，返回空消息列表');
        return [];
      }
      
      // 如果本地没有用户信息，尝试通过token获取
      if (!localStorage.getItem('user')) {
        const userProfile = await getUserProfileByToken();
        if (!userProfile || !userProfile.id) {
          console.warn('通过token获取用户信息失败，返回空消息列表');
          return [];
        }
      }
      
      const response = await axios.get<Conversation[]>(
        `${API_BASE_URL}/api/messages`,
        { headers: getAuthHeaders() }
      );
      return response.data;
    } catch (error) {
      console.error('获取对话列表失败:', error);
      return [];
    }
  }

  // 获取未读消息数量
  static async getUnreadMessageCount(): Promise<number> {
    try {
      const currentUserId = getCurrentUserId();
      if (!currentUserId) {
        console.warn('获取用户ID失败，返回0未读消息');
        return 0;
      }
      
      // 如果本地没有用户信息，尝试通过token获取
      if (!localStorage.getItem('user')) {
        const userProfile = await getUserProfileByToken();
        if (!userProfile || !userProfile.id) {
          console.warn('通过token获取用户信息失败，返回0未读消息');
          return 0;
        }
      }
      
      const response = await axios.get<{ count: number }>(
        `${API_BASE_URL}/api/messages/unread`,
        { headers: getAuthHeaders() }
      );
      return response.data.count;
    } catch (error) {
      console.error('获取未读消息数量失败:', error);
      return 0;
    }
  }

  // 标记消息为已读
  static async markMessagesAsRead(senderId: string): Promise<boolean> {
    try {
      const currentUserId = getCurrentUserId();
      if (!currentUserId) {
        console.warn('获取用户ID失败，无法标记消息为已读');
        return false;
      }
      
      // 如果本地没有用户信息，尝试通过token获取
      if (!localStorage.getItem('user')) {
        const userProfile = await getUserProfileByToken();
        if (!userProfile || !userProfile.id) {
          console.warn('通过token获取用户信息失败，无法标记消息为已读');
          return false;
        }
      }
      
      const response = await axios.put(
        `${API_BASE_URL}/api/messages/markAsRead/${senderId}`,
        {},
        { headers: getAuthHeaders() }
      );
      
      return response.status === 200;
    } catch (error) {
      console.error('标记消息为已读失败:', error);
      return false;
    }
  }

  // 删除与特定用户的所有对话
  static async deleteMessage(userId: string): Promise<boolean> {
    try {
      const currentUserId = getCurrentUserId();
      if (!currentUserId) {
        console.warn('获取用户ID失败，无法删除对话');
        return false;
      }
      
      // 如果本地没有用户信息，尝试通过token获取
      if (!localStorage.getItem('user')) {
        const userProfile = await getUserProfileByToken();
        if (!userProfile || !userProfile.id) {
          console.warn('通过token获取用户信息失败，无法删除对话');
          return false;
        }
      }
      
      const response = await axios.delete(
        `${API_BASE_URL}/api/messages/conversation/${userId}`,
        { headers: getAuthHeaders() }
      );
      
      return response.status === 200;
    } catch (error) {
      console.error('删除对话失败:', error);
      return false;
    }
  }
}